package com.sunyur.tailor.channel.web.outer.user.controller;

import com.alibaba.fastjson.JSON;
import com.sunyur.tailor.channel.common.middle.base.ChannelResult;
import com.sunyur.tailor.channel.common.middle.enums.MiddleResultEnum;
import com.sunyur.tailor.channel.service.inner.org.param.OrgSyncInfoParam;
import com.sunyur.tailor.channel.service.inner.user.param.UserSyncParam;
import com.sunyur.tailor.channel.service.inner.user.service.SunyurUserService;
import com.sunyur.tailor.channel.web.outer.user.dto.UserSyncInfoDTO;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author pengbing
 * @Description //人员数据控制层
 * @Date 15:45 2021/6/1
 * @Param
 * @return
 **/
@Log4j2
@RestController
@RequestMapping("/outer/user")
public class UserController {
    /**
     * 人员服务
     */
    @Autowired
    private SunyurUserService sunyurUserService;

    /**
     * 同步创建人员
     */
    @PostMapping(value = "/batchCreate", produces = MediaType.APPLICATION_JSON_VALUE)
    public ChannelResult batchCreate(@RequestBody @Valid List<UserSyncInfoDTO> userSyncInfoDTOS) {
        log.info("UserController batchCreate param:{}", JSON.toJSONString(userSyncInfoDTOS));
        ChannelResult result = new ChannelResult<>();
        if (CollectionUtils.isEmpty(userSyncInfoDTOS)) {
            log.error("UserController batchCreate param is null");
            result.setError(MiddleResultEnum.PARAM_NULL.getCode(), MiddleResultEnum.PARAM_NULL.getValue());
            return result;
        }
        try {
            List<UserSyncParam> userSyncParamList = getUserSyncInfoParams(userSyncInfoDTOS);
            result = sunyurUserService.syncUserList(userSyncParamList);
        } catch (Exception e) {
            log.error("UserController batchCreate exception:{}", e);
            result.setError(MiddleResultEnum.EXCEPTION.getCode(), MiddleResultEnum.EXCEPTION.getValue());
        }
        return result;
    }

    private List<UserSyncParam> getUserSyncInfoParams(List<UserSyncInfoDTO> userSyncInfoDTOS) {
        List<UserSyncParam> userSyncParamList =new ArrayList<>();
        userSyncInfoDTOS.forEach(items -> {
            UserSyncParam target = new UserSyncParam();
            BeanUtils.copyProperties(items, target);
            userSyncParamList.add(target);
        });
        return userSyncParamList;
    }
}